<template>
	<div class="search">
		<input type="text" v-model="inputValue" placeholder="输入城市名或拼音" class="search-input">
		<div class="search-result" ref="scrollList" v-show="inputValueEmpty">
			<ul>
				<li v-for="item in list" 
					class="result-list border-topbottom"
					@click="handleItemClick(item.name)"
				>
					{{item.name}}
				</li>
				<li class="result-list border-topbottom" v-show="!listEmpty">
					没有找到相应内容
				</li>
			</ul>
		</div>
	</div>
</template>

<script>
import Bscroll from 'better-scroll'
export default{
	name:'CitySearch',
	mounted(){
		this.scroll = new Bscroll(this.$refs.scrollList)
	},
	props:{
		cities:Object
	},
	methods:{
		handleItemClick:function(city){
			this.$store.commit('changeCity',city)
			this.$router.push('/')
		}
	},
	computed:{
		listEmpty(){
			return this.list.length
		},
		inputValueEmpty(){
			return this.inputValue
		}
	},
	data:function(){
		return {
			inputValue: '',
			list: [],
			timer: null
		}
	},
	watch:{
		inputValue(){
			if(this.timer){
				clearTimeout(this.timer)
			}
			this.timer=setTimeout(()=>{
				const result = []
				if(this.inputValue!=''){
					for(let key in this.cities){
						this.cities[key].forEach((item)=>{
							if(item.spell.indexOf(this.inputValue)>-1
								||item.name.indexOf(this.inputValue)>-1){
								result.push(item)
							}
						})
					}
				}
				this.list = result;
			},100)
		}
	}
}
</script>

<style lang="stylus" scoped>
	.border-topbottom
		&:before
			border-color: #ccc
		&:after
			border-color: #ccc
	.search
		height: .72rem
		background: #00bcd4
		padding: 0 .1rem
		.search-input
			height: .62rem
			box-sizing: border-box
			line-height: .62rem
			width: 100%
			text-align: center
			border-radius: .06rem
			color: #666
			padding: 0 .1rem
		.search-result
			position: absolute
			overflow: hidden
			z-index: 1
			top: 1.48rem
			bottom: 0
			left: 0
			right: 0
			background: #eee
			.result-list
				line-height: .6rem
				height: .6rem
				color: black
				padding-left: .2rem

</style>
